//
//  FLSAttractionsQuery.m
//  TripByMine
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 Shangyalei. All rights reserved.
//

#import "FLSAttractionsQuery.h"

#define kApi @"e46d2f955997e36dda176d1223c153d5"

@interface FLSAttractionsQuery ()

@property (nonatomic, strong) NSURLSession *session;

@property (nonatomic, strong) AppDelegate *app;

@end

@implementation FLSAttractionsQuery

// 景点查询
- (void)AttractionsQueryWithPlace:(NSString *)place Block:(void(^)(ScenicSearchModel *model))block
{
    _app = [[AppDelegate alloc] init];
    if ([_app internetReachableOrNot]) {
    [self.session invalidateAndCancel];
    NSString *Area = [self requestWithString:place];
    NSString *httpPar = [NSString stringWithFormat:@"id=%@&output=json", Area];
    NSString *httpUrl = @"http://apis.baidu.com/apistore/attractions/spot";
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, httpPar];
    NSURL *url = [NSURL URLWithString: urlStr];
    // 创建子线程,请求数据
    __block FLSAttractionsQuery *mySelf = self;
    // 创建子线程 做数据解析
   // dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 通过接口 获取数据 用数组接收
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
        [request setHTTPMethod: @"GET"];
        [request addValue: kApi forHTTPHeaderField: @"apikey"];
        ScenicSearchModel *model = [[ScenicSearchModel alloc] init];
        // xcode 7.0方法
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {
                NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                } else {
                mySelf.dictionary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
                    if ([[mySelf.dictionary valueForKey:@"status"] isEqualToString:@"Success"]) {
                        [model setValue:@"YES" forKey:@"state"];
                          NSDictionary *tempDict = [mySelf.dictionary valueForKey:@"result"];
                        [model setValuesForKeysWithDictionary:tempDict];
                        NSDictionary *dict = [tempDict valueForKey:@"ticket_info"];
                        [model setValuesForKeysWithDictionary:dict];
                    }
                  
                }
       
        // 回到主线程 结果回调
            dispatch_async(dispatch_get_main_queue(), ^{
                block(model);
            });
      }];
        [dataTask resume];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"🙅 您的当前网络中断或网络信号差, 请检查网络后重新进入!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
   // });
}


// 根据汉字转化为拼音
- (NSString *)requestWithString:(NSString *)area
{
    NSMutableString *mutableString = [NSMutableString stringWithString:area];
    
    CFStringTransform((CFMutableStringRef)mutableString, NULL,kCFStringTransformToLatin, false);
    
    mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    NSArray *arr = [mutableString componentsSeparatedByString:@" "];
    NSMutableString *muStr = [NSMutableString stringWithFormat:@""];
    for (NSString *str in arr) {
        [muStr appendString:str];
    }
    // 汉字转化为拼音成功
 
    return muStr;
}


@end
